import React, { useEffect, useState } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { message, Spin } from 'antd';
import { authService } from '../../services/auth';

const GiteeCallback: React.FC = () => {
    const [searchParams] = useSearchParams();
    const navigate = useNavigate();
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const code = searchParams.get('code');

        if (code) {
            handleGiteeAuth(code);
        } else {
            message.error('授权失败，请重试');
            navigate('/login');
        }
    }, [searchParams, navigate]);

    const handleGiteeAuth = async (code: string) => {
        try {
            setLoading(true);
            await authService.giteeLogin(code);
            message.success('Gitee登录成功');
            navigate('/mySelf', { replace: true });
        } catch (error) {
            console.error('Gitee登录失败:', error);
            message.error('Gitee登录失败，请重试');
            navigate('/login');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="callback-container" style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '100vh',
            flexDirection: 'column'
        }}>
            <Spin size="large" />
            <p style={{ marginTop: 16 }}>正在登录中...</p>
        </div>
    );
};

export default GiteeCallback;

